package top.littlejiang.onlinexam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import top.littlejiang.onlinexam.common.annotation.Log;
import top.littlejiang.onlinexam.common.base.BusinessException;
import top.littlejiang.onlinexam.common.utils.DateUtils;
import top.littlejiang.onlinexam.common.utils.JWTUtils;
import top.littlejiang.onlinexam.entity.OlexamRole;
import top.littlejiang.onlinexam.mapper.OlexamRoleMapper;
import top.littlejiang.onlinexam.service.OlexamMenuRoleService;
import top.littlejiang.onlinexam.service.OlexamRoleService;
import top.littlejiang.onlinexam.common.base.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * OlexamRole 服务实现类
 * </p>
 *
 * @author chen
 * @since 2020-12-26
 */
@Service
public class OlexamRoleServiceImpl extends BaseServiceImpl<OlexamRoleMapper, OlexamRole> implements OlexamRoleService {

    @Autowired
    OlexamMenuRoleService menuRoleService;

    /**
     * 根据条件查询所有角色
     *
     * @return
     */
    @Override
    public List<OlexamRole> getAll(OlexamRole role, boolean checkDel) {
        QueryWrapper wrapper = new QueryWrapper();
        if (!Objects.isNull(role) && StringUtils.isNotEmpty(role.getRoleName())) {
            wrapper.like("role_name", role.getRoleName());
        }
        if (checkDel) {
            wrapper.eq("is_del", 0);
        }
        wrapper.orderByAsc("id");
        return this.list(wrapper);
    }

    /**
     * 更新角色及对应的菜单列表
     *
     * @param role
     */
    @Log("更新角色")
    @Override
    public void updateOrInsert(OlexamRole role) {
        if (Objects.isNull(role)){
            throw new BusinessException("更新角色失败，参数异常！");
        }
        role.setUpdateTime(DateUtils.getTime());
        role.setCreateUser(JWTUtils.getUserName());
        this.saveOrUpdate(role);
        List<Integer> newMenus = role.getMenus();
        menuRoleService.insertOrDelete(newMenus, role.getId());
    }
}
